<template>
  <div  style="background-color: #eaedf1;">
<!--    面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right" >
<!--      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>-->
      <el-breadcrumb-item>员工管理</el-breadcrumb-item>
      <el-breadcrumb-item>员工列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片区域-->
    <el-card>
<!--     搜索与添加区域 -->
      <el-row :gutter="20" >
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getEmployeeList">
            <el-button slot="append" icon="el-icon-search" @click="getEmployeeList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加员工</el-button>
        </el-col>
      </el-row>
<!--     用户列表区域 -->
      <el-table
        :data="employeelist"
        style="width: 100%"
        border
        stripe>
<!-- 添加索引列 直接把type属性设置成index即可-->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="epName" label="姓名"></el-table-column>
        <el-table-column label="照片">
          <template slot-scope="scope">
            <el-image
              style="width: 60px; height: 70px"
              :src="scope.row.epPhoto"
              fit="fill"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="epJob" label="岗位"></el-table-column>
        <el-table-column prop="epPaiban" label="排班"></el-table-column>
        <el-table-column prop="epMobile" label="联系方式"></el-table-column>
        // 指定好作用域插槽，就不用prop绑定用户列表数据项了，因为prop会被作用域插槽覆盖
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
<!--          编辑按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.epId)">修改</el-button>
<!--          删除按钮  -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="showdDeleteTip(scope.row.epId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
<!--      分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
<!--   添加用户对话框区域 -->
    <el-dialog
      title="添加员工"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addFormClosed">
<!--      内容主体区域-->
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="姓名" prop="epName">
          <el-input v-model="addForm.epName"></el-input>
        </el-form-item>
        <el-form-item label="照片" prop="epPhoto">
          <el-input v-model="addForm.epPhoto" autocomplete="off" placeholder="图片URL"></el-input>
          <img-upload @onUpload="uploadImg" ref="imgUpload"></img-upload>
        </el-form-item>
        <el-form-item label="职位" prop="epJob">
          <el-input v-model="addForm.epJob"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="epMobile">
          <el-input v-model="addForm.epMobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="epEmail">
          <el-input v-model="addForm.epEmail"></el-input>
        </el-form-item>
        <el-form-item label="排班" prop="epPaiban">
          <el-checkbox-group
            v-model="checkedDates"
            :min="0"
            :max="10">
            <el-checkbox v-for="date in Dates" :label="date" :key="date">{{date}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div>{{addForm.epPaiban}}</div>
<!--      底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addEmployee">确 定</el-button>
      </span>
    </el-dialog>
<!--    修改用户对话框区域-->
<!--    :before-close="handleClose"-->
    <el-dialog
      title="修改员工信息"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editFormClosed">
      <!--      内容主体区域-->
      <el-form ref="editFormRef" :model="editForm" :rules="addFormRules" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="editForm.epName" :disabled="true" :placeholder="editForm.epName"></el-input>
        </el-form-item>
        <el-form-item label="照片" prop="epPhoto">
          <el-input v-model="editForm.epPhoto" :placeholder="editForm.epPhoto"></el-input>
          <img-upload @onUpload="uploadEditImg" ref="imgEditUpload"></img-upload>
        </el-form-item>
        <el-form-item label="职位" prop="epJob">
          <el-input v-model="editForm.epJob" :placeholder="editForm.epJob"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="epMobile">
          <el-input v-model="editForm.epMobile" :placeholder="editForm.epMobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="epEmail">
          <el-input v-model="editForm.epEmail" :placeholder="editForm.epEmail"></el-input>
        </el-form-item>
        <el-form-item label="排班" prop="epPaiban">
          <el-checkbox-group
            v-model="checkedDatesById"
            :min="0"
            :max="10">
            <el-checkbox v-for="date in Dates" :label="date" :key="date">{{date}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editEmployeeInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs'
import ImgUpload from '../ImgUpload.vue'
export default {
  name: 'Employee',
  components: {ImgUpload},
  // dateList: ['星期一上午8:00-12:00', '星期一下午13:00-18:00', '星期二上午8:00-12:00', '星期二下午13:00-18:00', '星期三上午8:00-12:00', '星期三下午13:00-18:00', '星期四上午8:00-12:00', '星期四下午13:00-18:00', '星期五上午8:00-12:00', '星期五下午13:00-18:00'],
  // dateList: ['星期一上午8:00-12:00', '星期一下午13:00-18:00'],
  data () {
    // 验证邮箱的校验规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      let regEmail = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
      if (regEmail.test(value)) return cb()
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的校验规则
    var checkMobile = (rule, value, cb) => {
      let regMobile = /^1[3|4|5|7|8][0-9]\d{8}$/
      if (regMobile.test(value)) return cb()
      cb(new Error('请输入合法的手机'))
    }
    return {
      fileList: [],
      checkedDatesById: [],
      checkedDates: [],
      Dates: ['星期一上午8:00-12:00', '星期一下午13:00-18:00', '星期二上午8:00-12:00', '星期二下午13:00-18:00', '星期三上午8:00-12:00', '星期三下午13:00-18:00', '星期四上午8:00-12:00', '星期四下午13:00-18:00', '星期五上午8:00-12:00', '星期五下午13:00-18:00'],
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      employeelist: [],
      total: 0,
      addDialogVisible: false,
      // 控制编辑用户对话框得显示与否
      editDialogVisible: false,
      // 控制分配角色对话框的显示与否
      setRoleDialogVisible: false,
      // 添加用户的表单数据对象
      addForm: {
        epName: '',
        epPhoto: '',
        epPaiban: '',
        epJob: '',
        epMobile: '',
        epEmail: ''
      },
      userInfo: {},
      // 添加表单的验证规则对象
      addFormRules: {
        // 用户名的验证规则
        epName: [
          {
            required: true, message: '请输入姓名', trigger: 'blur'
          },
          {
            min: 3, max: 10, message: '用户名长度在3~10个字符之间', trigger: 'blur'
          }
        ],
        epPhoto: [
          {
            required: true, message: '请上传60*70像素的照片', trigger: 'blur'
          }
        ],
        epJob: [
          {
            required: true, message: '请输入职位', trigger: 'blur'
          }
        ],
        epMobile: [
          {
            required: true, message: '请输入手机', trigger: 'blur'
          },
          {
            validator: checkMobile, trigger: 'blur'
          }
        ]
      },
      // 查询用户信息保存得对象
      editForm: {}
    }
  },
  created () {
    this.getEmployeeList()
  },
  methods: {
    uploadEditImg () {
      this.editForm.epPhoto = this.$refs.imgEditUpload.url
      console.log(this.editForm.epPhoto)
    },
    uploadImg () {
      this.addForm.epPhoto = this.$refs.imgUpload.url
      console.log(this.addForm.epPhoto)
    },
    getEmployeeList () {
      this.$axios.get('employee', {params: this.queryInfo})
        .then(resp => {
          if (resp && resp.data.status === 200) {
            this.employeelist = resp.data.data.data
            this.total = resp.data.data.totalpage
            console.log(resp.data.data)
          }
        })
    },
    // 监听每页显示数量变化函数
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      // 每页显示数量变化后 重新请求用户列表
      this.getEmployeeList()
    },
    // 监听当前页码变化函数
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getEmployeeList()
    },
    // switch开关状态发生变化时的回调函数
    async changeSwitch (userInfo) {
      console.log(userInfo)
      const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('修改用户状态失败!')
      }
      this.$message.success('更新状态成功!')
    },
    // 监听 添加用户对话框的关闭 事件
    addFormClosed () {
      // 关闭时 表单重置
      this.$refs.addFormRef.resetFields()
    },
    addEmployee () {
      // validate 对整个表单进行验证 参数为一个回调函数 回调函数得第一个参数为验证是否成功变量
      this.$refs.addFormRef.validate(valid => {
        // 若验证不通过，则什么也不做 直接返回
        if (!valid) return
        // 发起网络请求 添加新用户
        // 把日期范围数组转化为拼接字符串
        this.addForm.epPaiban = this.checkedDates.join(',')
        this.$axios
          .post('employee', qs.stringify(this.addForm), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
          .then(resp => {
            console.log(resp.data)
            if (resp.data.status !== 200) this.$message.error('添加员工失败!')
            this.addDialogVisible = false
            this.getEmployeeList()
            this.$message.success('添加员工成功')
          })
      })
    },
    // 这里显示原来的用户表单数据，不建议从本地scope.row获取 使用后端根据id获取用户信息接口
    showEditDialog (id) {
      this.$axios
        .get('employee/' + id)
        .then(resp => {
          if (resp.data.status !== 200) this.$message.error('获取员工失败!')
          console.log(resp.data.data)
          this.editForm = resp.data.data
          this.checkedDatesById = resp.data.data.epPaiban.split(',')
          this.fileList = [{name: this.editForm.epName + '.jpg', url: this.editForm.epPhoto}]
          console.log(this.editForm.epPaiban)
          // 显示编辑对话框
          this.editDialogVisible = true
        })
    },
    // 监听 编辑用户对话框的 关闭事件
    editFormClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editEmployeeInfo () {
      // validate 对整个表单进行验证 参数为一个回调函数 回调函数得第一个参数为验证是否成功变量
      this.$refs.editFormRef.validate(async valid => {
        // 若验证不通过，则什么也不做 直接返回
        if (!valid) return
        this.editForm.epPaiban = this.checkedDatesById.join(',')
        // 发起网络请求 修改用户信息
        this.$axios
          .put('employee', qs.stringify(this.editForm), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
          .then(resp => {
            console.log(resp.data)
            if (resp.data.status !== 200) this.$message.error('更新员工信息失败!')
            this.editDialogVisible = false
            // 重新获取用户列表数据
            this.getEmployeeList()
            this.$message.success('修改员工信息成功')
          })
      })
    },
    showdDeleteTip (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios
          .delete('employee/' + id)
          .then(resp => {
            console.log(resp.data)
            if (resp.data.status !== 200) return this.$message.error('删除失败')
            this.getEmployeeList()
          })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 显示分配角色对话框的函数
    async showSetRoleDialog (userInfo) {
      this.userInfo = userInfo
      // 在展示分配角色对话框之前 先获取所有角色列表
      const {data: res} = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败!')
      console.log('rolelist')
      console.log(res.data)
      this.roleslist = res.data
      this.setRoleDialogVisible = true
    },
    // 点击确定按钮时 将用户分配角色信息提交到后端
    async setRoles (userInfo) {
      if (!this.choosedRoleId) {
        return this.$message.error('请选择要分配的角色!')
      }
      const {data: res} = await this.$http.put(`users/${userInfo.id}/role`, {
        rid: this.choosedRoleId
      })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败!')
      this.setRoleDialogVisible = false
      this.$message.success('分配角色成功')
      console.log('put role')
      console.log(res)
      // 点击确认之后 清空已经选择的角色
      this.choosedRoleId = ''
      // 重新获取用户列表
      this.getUserList()
    },
    setRolesDialogClosed () {
      // 关闭分配角色对话框之前 要清空已经选择的角色
      this.choosedRoleId = ''
    }
  }
}
</script>

<style lang = "less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 12px;
}
.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
  font-size: 13px;
}
/*.image{
  width: 60px;
  height: 70px;
}*/
</style>
